package gr.atc.epart;

import gr.atc.epart.CustomCategoriesManager.CustomTabData;
import gr.atc.epart.actions.Petition;
import gr.atc.epart.actions.PetitionSignature;
import gr.atc.epart.actions.Action.Type;
import gr.atc.epart.googlewrapper.GoogleServiceCallbackType;
import gr.atc.epart.googlewrapper.accounts.GoogleAccountCredentialStorage;
import gr.atc.epart.googlewrapper.calendar.Calendar;
import gr.atc.epart.googlewrapper.moderator.GoogleModerator;
import gr.atc.epart.googlewrapper.moderator.ModeratorSeries;
import gr.atc.epart.googlewrapper.moderator.ModeratorSubmission;
import gr.atc.epart.googlewrapper.moderator.ModeratorTopic;
import gr.atc.epart.googlewrapper.moderator.ModeratorVote;
import gr.atc.epart.googlewrapper.picassaweb.PicassaWeb;
import gr.atc.epart.googlewrapper.youtube.YouTube;
import gr.atc.epart.googlewrapper.youtube.YouTubeVideoComment;
import gr.atc.epart.googlewrapper.youtube.YouTubeVideoEntry;
import gr.atc.epart.net.ActionsPage;
import gr.atc.epart.net.CreateFailedException;
import gr.atc.epart.net.RetrievalFailedException;
import gr.atc.epart.net.ActionsPage.SortBy;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.simple.JSONObject;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.util.Pair;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.TabHost;
import android.widget.Toast;

public class EPartDesktopActivity extends TabActivity // implements TabContentFactory
{
	
	EPartClient client = new EPartClient();
	TabHost tabHost = null;
	
	String username;

	private static final int CREATE_ACTION_ID = 0;
	private static final int SETTINGS_ID = 1;
	private static final int ADD_CATEGORY_ID = 2;
	private static final int ADD_CATEGORY_CODE = 0;

	///
	/// THIS IS A DEMO...SEPERATE ACTIVITIES ARE REQUIRED TO HANDLE THE EVENTS
	///
	///
	 private Calendar _calendar; 
	 private YouTube  _youtube;
	 private PicassaWeb  _picassaWeb;
	 private GoogleModerator _moderator; 
	 
	 //
	 // used to receive callbacks related to calendars only  
	 //
	 private Handler _messageHandler = new Handler() 
	  {
	      public void handleMessage(Message msg) 
	      {  
	          switch(msg.what) 
	          {
	        	  //
	        	  // Google Calendar
	        	  //
	        	  case GoogleServiceCallbackType.CalendarServiceIsReady:
	        		  // we are free to receive the calendars
	        		  _calendar.retrieveCalendars();
	        		  break;
	        	  
	        	  case GoogleServiceCallbackType.UserAuthenticationRequired:
	        		  //
	        		  // start an activity to authenticate the user
	        		  //
	        		  //
	        		  // there should be a descrimination for which service we are authenticating
	        		  _moderator.authenticate("tsakonas.nick@gmail.com","m4l4k13$");
	        		  break;

	        	  case GoogleServiceCallbackType.CalendarFeedsReceived:
	        		  // calendars received...
	        		  // this is an example of what we can do...
	        		  _calendar.retrieveEventsForFeed("tsakonas.nick@gmail.com");
	        		  break;

	        	  case GoogleServiceCallbackType.CalendarFeedEventsReceived:
	        		  // this is an example of what we can do...
	        		  _calendar.addEventToFeed("tsakonas.nick@gmail.com");
	        		  break;
	        	  case GoogleServiceCallbackType.CalendarEventAdded:
	        		  
	        		  break;

	        		  //
	        		  // Google YouTube
	        		  //
	        		  //
	        	  case GoogleServiceCallbackType.YouTubeServiceIsReady:
	        		  
	        		  // this is an example of what we can do...

	        		  //
	        		  // test 1...search
	        		  _youtube.search("metallica");
	        		  
	        		  
	        		  //
	        		  // test 2 .. upload
	        		  //
	        		  //String[] tags = {"android","youtube API"};
	        		  //try
	        		  //{
	        		  //	  _youtube.uploadVideo("/sdcard/DCIM/100MEDIA/VIDEO0002.3gp", "Video 1 from android", "testing upload API","Education", tags);
	        		  // }
	        		  //catch(Exception e)
	        		  //{
	        		  //	  
	        		  // }
	        		  
	        		  //
	        		  // test 3 ... get subscriptions
	        		  //
	        		  //_youtube.getSubscriptions();
	        		  
	        		  break;
	        	 
	        	  case GoogleServiceCallbackType.YouTubeVideoFeedsReceived:
	        		  
	        		  ArrayList<YouTubeVideoEntry> videos = (ArrayList<YouTubeVideoEntry>) msg.getData().getSerializable("VIDEOS");

	        		  // this is an example of what we can do...

	        		  /*
	        		  int videosReturned = videos.size();
	        		  
	        		  for (YouTubeVideoEntry video:videos)
	        		  {
	        			  String url = video.getVideoUrl();
	        			  String title = video.getVideoTitle();
	        			  int duration = video.getDuration();
	        			  
	        			  String thumb = video.getThumbnailsUrls().get(0).getThumbnailUrl();
	        			  int width = video.getThumbnailsUrls().get(0).getWidth();
	        			  int height = video.getThumbnailsUrls().get(0).getHeight();
	        			  String timestamp = video.getThumbnailsUrls().get(0).getTimestamp(); 	
	        		  }
	        		  */

	        		  /*
   	        		   YouTubeVideoEntry video = videos.get(0);
	        		  _youtube.rate(video.getRatingsUrl(),4);
	        		   */
	        		  
	        		  
	        		  /*
	        		  YouTubeVideoEntry video = videos.get(1);
	        		  _youtube.rateAsLike(video.getRatingsUrl());
	        		  */

	        		   
	        		  YouTubeVideoEntry video = videos.get(3);
	        		  _youtube.getComments(video.getCommentsUrl());
	        		  
	        		  
	        		 // YouTubeVideoEntry video = videos.get(2);
	        		 // _youtube.submitComment(video.getCommentsUrl(),"One of the best metal bands ever!!!");

	        		  break;

	        	  case GoogleServiceCallbackType.YouTubeVideoRatingPosted:
	        		  
	        		  	break;

	        	  case GoogleServiceCallbackType.YouTubeVideoCommentsReceived:

	        		    ArrayList<YouTubeVideoComment> comments = (ArrayList<YouTubeVideoComment>) msg.getData().getSerializable("COMMENTS");
	        		  
  	        		  // this is an example of what we can do...

	        		    YouTubeVideoComment comment = comments.get(4);
	        		    _youtube.replyToComment(comment.getCommentsUrl(), comment.getReplyToUrl(), "Who is Bieber? Is he the pop I-am-here-today-nobody-knows-me-tommorow 12-year old child?");
	        		   
	        		  	break;
	        	
	        	  case GoogleServiceCallbackType.YouTubeVideoCommentPosted:
	        		  	
	        		   break;
	        		  	
	        	  case GoogleServiceCallbackType.YouTubeVideoCommentReplyPosted:
	        		  
	        		  break;
	        		  	
	        	  case  GoogleServiceCallbackType.YouTubeVideoContentUploaded:
	        		  
	        		  break;
	        		  
	        	  case GoogleServiceCallbackType.YouTubeSubscriptionsReceived:
	        		  
	        		  break;
	        		  
	        		  //
	        		  //  Google Picassa
	        		  //
	        	  case GoogleServiceCallbackType.PicassaWebServiceIsReady:
	        		  // this is an exmaple
	        		  _picassaWeb.getAlbums();
	        		  break;
	        		  
	        		  //
	        		  // Google Moderator
	        		  //
	        		
	        	  case GoogleServiceCallbackType.ModeratorServiceIsReady:
	        		  try
	        		  {
	        			  _moderator.getSeries("http://www.google.com/moderator/#15/e=2233b");
	        		  }	 catch (MalformedURLException e)
	        		  {
	        			  // TODO Auto-generated catch block
	        			  e.printStackTrace();
	        		  }
	        		  break;
	        		  
	        	  case GoogleServiceCallbackType.ModeratorSeriesReceived:
		    			
	        		  ArrayList<ModeratorSeries> seriesList = (ArrayList<ModeratorSeries>) msg.getData().getSerializable("SERIES");
	        		  
	        		  // the list is used for future use...in order to retrieve more than one series at a time
	        		  // at the moment only one series is contained
	        		  ModeratorSeries series = seriesList.get(0);
	        		  
		    		  if (series.shouldRetrieveTopics())
		    			_moderator.getTopics(series);
		    		  
		    		  
	        		  break;

	        	  case GoogleServiceCallbackType.ModeratorSeriesTopicsReceived:
	        		  
	        		  ArrayList<ModeratorTopic> topics = (ArrayList<ModeratorTopic>) msg.getData().getSerializable("TOPICS");

	        		  try
	        		  {
	        			int kkk=1;
	        			
		    			for (ModeratorTopic topic: topics)
		    			{
		    				String name = topic.getName();
		    				String description = topic.getDescription();
		    				List<ModeratorSubmission> submisions = topic.getSubmissionList();
		    				
		    				for (ModeratorSubmission subm:submisions)
		    				{
		    					String submTest = subm.getText();
		    					int plus = subm.getCounter(ModeratorSubmission.PLUS_VOTES);
		    					int minus = subm.getCounter(ModeratorSubmission.MINUS_VOTES);
		    					
		    					kkk++;
		    					ModeratorVote.VoteFlag flg=ModeratorVote.VoteFlag.Ok;
		    					
		    					if (kkk == 8)
		    						flg= ModeratorVote.VoteFlag.Inappropriate;
		    					
		    					ModeratorVote vote = new ModeratorVote(ModeratorVote.Vote.Minus,flg);
		    					_moderator.voteSubmission(subm, vote);
		    				}
		    			}
	        			
	        			//  ModeratorTopic topic = topics.get(1);
		    			//  _moderator.addSubmision(topic, "nikos", "the best place for summer vacation", "Athens,Greece", "http://www.youtube.com/watch?v=Ethv_eLk0Tc");

						  _moderator.addSeries("Worst food to eat", "Describe the worst food you have ever had!!!", false);	

	        		  }catch (Exception e)
	        		  {
	        			  
	        		  }
	        		  
	        		  break;
	        		  
	        	  case GoogleServiceCallbackType.ModeratorSubmissionAdded:
	        		  
	        		  break;

				 case GoogleServiceCallbackType.ModeratorSubmissionVoteAdded:
					 
					  break;

				 case GoogleServiceCallbackType.ModeratorNewSeriesAdded:

	        		  ArrayList<ModeratorSeries> newSeriesList = (ArrayList<ModeratorSeries>) msg.getData().getSerializable("SERIES");
	        		  
	        		  // the list is used for future use...in order to retrieve more than one series at a time
	        		  // at the moment only one series is contained
	        		  ModeratorSeries newSeries = newSeriesList.get(0);

					  _moderator.addTopic(newSeries, "FishFood", "shell food, bliax!!!", null);
					  
					  break;

	        	  case GoogleServiceCallbackType.OperationError:
	        		  //_ownerCallback.sendMessage(msg);
	        		  break;
	          }
	      }
	  };

	
	///
	/// END OF DEMO
	///
	///
	
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		
		username = AccountUtil.getAccountName(this.getBaseContext());
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		tabHost = getTabHost();

		tabHost.getTabWidget().setHorizontalScrollBarEnabled(true);

		retrieveActions(null, null, "all", null, null, "Popularity", "All",
				"Popular");

		tabHost = getTabHost();
		tabHost.addTab(tabHost.newTabSpec("Popular").setIndicator("Popular",
				getResources().getDrawable(android.R.drawable.star_big_off))
				.setContent(new Intent(this, ActionsViewActivity.class)));

		retrieveActions(null, null, username, null, null, "Popularity",
				"All", "Mine");

		tabHost.addTab(tabHost.newTabSpec("Mine")
				.setIndicator(
						"Mine",
						getResources().getDrawable(
								android.R.drawable.ic_menu_myplaces))
				.setContent(new Intent(this, ActionsViewActivity.class)));

		tabHost.addTab(tabHost.newTabSpec("Search").setIndicator("Search",
				getResources().getDrawable(android.R.drawable.ic_menu_search))
				.setContent(new Intent(this, SearchActivity.class)));

		tabHost.addTab(tabHost.newTabSpec("Maps").setIndicator("Maps",
				getResources().getDrawable(android.R.drawable.ic_menu_mapmode))
				.setContent(new Intent(this, EPartMaps.class)));

		addCategories();
		//testCalendar();
		//testYouTube();
		//testPicassaWeb();
		//testModerator();

		
	}
	
	private void testCalendar()
	{
		try
		{
			// 
			// 
			// 
			_calendar = new Calendar(this,_messageHandler);
			_calendar.authenticate();
			
		}catch (Exception e )
		{
			Log.i("testCalendar()", e.getMessage() );
		}
		
	}

	private void testYouTube()
	{
		try
		{
			// 
			// 
			// 
			_youtube = new YouTube(this,_messageHandler);
			_youtube.authenticate();
			
		}catch (Exception e )
		{
			Log.i("testYouTube()", e.getMessage() );
		}
		
	}

	private void testPicassaWeb()
	{
		try
		{
			// 
			// 
			// 
			_picassaWeb = new PicassaWeb(this,_messageHandler);
			_picassaWeb.authenticate();
			
		}catch (Exception e )
		{
			Log.i("testPicassaWeb()", e.getMessage() );
		}
		
	}
	
	private void testOpenSocial()
	{
		try 
		{
			Intent actionDetailsIntent = new Intent();
			actionDetailsIntent.setClassName("gr.atc.epart",
			"gr.atc.epart.opensocial.FriendListActivity");
			startActivity(actionDetailsIntent);
			
		}catch (Exception e) 
		{
			Log.i("FiendListActivity", e.getMessage());
		}

	}

	
	private void testModerator()
	{
		try
		{
			// 
			// 
			//
			_moderator = new GoogleModerator(_messageHandler);
			// this will attempt to use existing credentials...if this is not possible
			// the activity should handle it
			_moderator.authenticate();
			
		}catch (Exception e )
		{
			Log.i("testModerator()", e.getMessage() );
		}
		
	}
	
	private void retrieveActions(String _nameString, String _tagsString,
			String _creatorString, String _fromString, String _toString,
			String _sortByString, String _typeString, String tabTag) {

		SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");

		Date _startDate = null;
		Date _endDate = null;

		try {
			if (_fromString != null && !_fromString.equals("")) {
				_startDate = formatter.parse(_fromString);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		try {
			if (_toString != null && !_toString.equals("")) {
				_endDate = formatter.parse(_toString);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Type type = Type.valueOf(_typeString);
		String[] _tags;
		if (_tagsString != null) {
			_tags = _tagsString.split(" ");
		} else {
			_tags = null;
		}

		ActionsPage actions = client.getActions(type, _creatorString,
				_startDate, _endDate, _tags, SortBy.Popularity, 1, 10);

		if (actions != null) {
			EPartVolatileDataStore.getInstance().setActionsList(tabTag,
					actions.getActions());
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(Menu.NONE, CREATE_ACTION_ID, Menu.NONE, "Create Action");
		menu.add(Menu.NONE, ADD_CATEGORY_ID, Menu.NONE, "Categories");
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		case CREATE_ACTION_ID:
			Intent actionDetailsIntent = new Intent();
			actionDetailsIntent.setClassName("gr.atc.epart",
					"gr.atc.epart.CreateActionActivity");
			startActivity(actionDetailsIntent);
			return true;

		case SETTINGS_ID:
			Intent settingsIntent = new Intent();
			settingsIntent
					.setClassName("gr.atc.epart", "gr.atc.epart.Settings");
			startActivity(settingsIntent);
			return true;

		case ADD_CATEGORY_ID:

			tabHost.setCurrentTab(0);
			Intent addCategoryIntent = new Intent();
			addCategoryIntent.setClassName("gr.atc.epart",
					"gr.atc.epart.CategoryMgrActivity");
			startActivityForResult(addCategoryIntent, ADD_CATEGORY_CODE);
			return true;

		default:
			return false;
		}

	}

	private void updateTabs() {

		tabHost = getTabHost();
		tabHost.clearAllTabs();

		tabHost.addTab(tabHost.newTabSpec("Popular").setIndicator("Popular",
				getResources().getDrawable(android.R.drawable.star_big_off))
				.setContent(new Intent(this, ActionsViewActivity.class)));

		tabHost.addTab(tabHost.newTabSpec("Mine")
				.setIndicator(
						"Mine",
						getResources().getDrawable(
								android.R.drawable.ic_menu_myplaces))
				.setContent(new Intent(this, ActionsViewActivity.class)));

		tabHost.addTab(tabHost.newTabSpec("Search").setIndicator("Search",
				getResources().getDrawable(android.R.drawable.ic_menu_search))
				.setContent(new Intent(this, SearchActivity.class)));

		tabHost.addTab(tabHost.newTabSpec("Maps").setIndicator("Maps",
				getResources().getDrawable(android.R.drawable.ic_menu_mapmode))
				.setContent(new Intent(this, EPartMaps.class)));

		addCategories();

	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) {

		case 200:
			updateTabs();
			break;

		default:
			break;
		}
	}

	protected void addCategories() {

		CustomCategoriesManager categoryManager = new CustomCategoriesManager(
				this);
		int numberOfCategories = categoryManager.getCustomTabsNumber();

		for (int i = 0; i < numberOfCategories; i++) {
			CustomTabData tabData = categoryManager.getCustomTabData(i);
			ActionsPage actions = client.getActions(tabData.getActionType(),
					tabData.getCreator(), tabData.getStartDate(), tabData
							.getStopDate(), tabData.getTags(), tabData
							.getSortBy(), tabData.getPageNumber(), tabData
							.getPageSize());

			if (actions != null) {
				EPartVolatileDataStore.getInstance().setActionsList(
						tabData.getTabName(), actions.getActions());

				tabHost = getTabHost();

				tabHost
						.addTab(tabHost
								.newTabSpec(tabData.getTabName())
								.setIndicator(
										tabData.getTabName(),
										getResources()
												.getDrawable(
														android.R.drawable.ic_menu_view))
								.setContent(
										new Intent(this,
												ActionsViewActivity.class)));

			}
		}

	}
}
